package com.ruoyi.web.controller.cs;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BasicsController;
import com.ruoyi.common.enums.WeaponType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.yyyoupin.RSAUtils;
import com.ruoyi.common.yyyoupin.bean.CSGOKnife;
import com.ruoyi.common.yyyoupin.bean.SaleResponse;
import com.ruoyi.common.yyyoupin.bean.SaleResponseVo;
import com.ruoyi.cs.domain.TGoodsPool;
import com.ruoyi.cs.mapper.TGoodsPoolMapper;
import com.ruoyi.cs.service.CommonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Type;
import java.util.List;
import java.util.stream.Collectors;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;

@Slf4j
@Api(tags = {"悠悠有品测试接口"})
@RestController
@RequestMapping("/cs/yy")
@SuppressWarnings("all")
public class YYYOUTestController extends BasicsController {
    @Autowired
    private TGoodsPoolMapper tGoodsPoolMapper;
    @Autowired
    private CommonService commonService;

    @ApiOperation("查询模板ID")
    @GetMapping(value = "/common/templateQuery")
    /**查询模板ID*/
    public String templateQuery(){
        String url = "https://gw-openapi.youpin898.com/open/v1/api/templateQuery";
        Map<String, Object> params = RSAUtils.toParams();
        params.put("sign",RSAUtils.getSign(params));
        return  RSAUtils.toPost(url,params);

    }
    @ApiOperation("查询商品列表")
    @GetMapping(value = "/common/goodsQuery")
    /**查询商品列表*/
    public  String goodsQuery(String templateId){
        String url = "https://gw-openapi.youpin898.com/open/v1/api/goodsQuery";
        Map<String, Object> params = RSAUtils.toParams();
        params.put("templateId", templateId);
        params.put("sign",RSAUtils.getSign(params));
        return  RSAUtils.toPost(url,params);
    }

    @ApiOperation("读取文件")
    @GetMapping(value = "/common/exportFileContent")
    public long exportFileContent() {
        String filePath = "C:\\Users\\Lenovo\\Desktop\\20231126124220_99b1ca9.txt";
        try {
            List<CSGOKnife> items = readItemsFromFile(filePath);
            int count = 0;
            if (items != null) {
                int batchSize = 100;
                int totalItems = items.size();
                for (int i = 0; i < totalItems; i += batchSize) {
                    count++;
                    int endIndex = Math.min(i + batchSize, totalItems);
                    List<CSGOKnife> batch = items.subList(i, endIndex);
                    // 将当前批次的数据保存到数据库中的操作
//                    saveBatchToDatabase(batch);
                    //更新商品价格
                    updateTGoodsPoolpPrice(batch.stream().map(CSGOKnife::getId).collect(Collectors.toList()));
                }
            }
            return count;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    private static List<CSGOKnife> readItemsFromFile(String filePath) throws IOException {
        StringBuilder content = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                content.append(line);
            }
        }

        Gson gson = new Gson();
        Type itemType = new TypeToken<List<CSGOKnife>>() {}.getType();
        return gson.fromJson(content.toString(), itemType);
    }

    private  void saveBatchToDatabase(List<CSGOKnife> knifeList) {
        List<TGoodsPool> tGoodsPools = new ArrayList<>();
        knifeList.forEach(csgo -> {
            TGoodsPool tGoodsPool = new TGoodsPool();
            tGoodsPool.setGoodsName(csgo.getName());
            tGoodsPool.setMarketHashName(csgo.getHashName());
            tGoodsPool.setGoodsMold(WeaponType.getTypeName(csgo.getTypeName()).getCode());
            tGoodsPool.setZBT(csgo.getId());
            tGoodsPool.setGoodsPrice(BigDecimal.ZERO);
            tGoodsPool.setGoodsExprice(BigDecimal.ZERO);
            tGoodsPool.setGoodsChance(new BigDecimal("0.01"));
            tGoodsPool.setGoodsStocknum(999L);
            tGoodsPool.setGoodsPutnum(999L);
            tGoodsPool.setGoodsType("0");
            tGoodsPool.setGoodsGrate("0");
            tGoodsPool.setCreateTime(DateUtils.getNowDate());
            tGoodsPools.add(tGoodsPool);
        });
        tGoodsPoolMapper.insertTGoodsPoolBatch(tGoodsPools);
    }

    /**更新商品价格*/
    public void updateTGoodsPoolpPrice(List<Integer> templateIds){
        String url = "https://gw-openapi.youpin898.com/open/v1/api/batchGetOnSaleCommodityInfo";
        Map<String, Object> params = RSAUtils.toParams();
        List<Map<String, Integer>> requestList = new ArrayList<>();
        templateIds.forEach(id -> {
            Map<String, Integer> map = new HashMap<>();
            map.put("templateId",id);
            requestList.add(map);
        });
        params.put("requestList",requestList);

        params.put("sign",RSAUtils.getSign(params));
        log.info("批量查询商品价格请求参数：{}",JSON.toJSONString(params));
        String body = RSAUtils.toPost(url,params);
        JSONObject jsonObject = JSON.parseObject(body);
        JSONArray array = jsonObject.getJSONArray("data");
        Gson gson = new Gson();
        List<SaleResponse> list = gson.fromJson(array.toString(), new TypeToken<List<SaleResponse>>(){}.getType());
        if(CollectionUtil.isNotEmpty(list)){
            List<SaleResponseVo> saleResponseVoList = commonService.toSaleResponseVo(list);
            tGoodsPoolMapper.updateTGoodPsoolPriceYY(saleResponseVoList);
        }

    }

    public List<SaleResponseVo> toSaleResponseVo(List<SaleResponse> list){
        return list.stream().map(saleResponse  -> SaleResponseVo.builder()
                .templateId(saleResponse.getSaleTemplateResponse().getTemplateId())
                .templateHashName(saleResponse.getSaleTemplateResponse().getTemplateHashName())
                .iconUrl(saleResponse.getSaleTemplateResponse().getIconUrl())
                .exteriorName(saleResponse.getSaleTemplateResponse().getExteriorName())
                .rarityName(saleResponse.getSaleTemplateResponse().getRarityName())
                .qualityName(saleResponse.getSaleTemplateResponse().getQualityName())
                .minSellPrice(saleResponse.getSaleCommodityResponse().getMinSellPrice())
                .fastShippingMinSellPrice(saleResponse.getSaleCommodityResponse().getFastShippingMinSellPrice())
                .referencePrice(saleResponse.getSaleCommodityResponse().getReferencePrice())
                .sellNum(saleResponse.getSaleCommodityResponse().getSellNum()).build()
        ).collect(Collectors.toList());
    }
}
